package com.wanho.qz103.hrsaas.commons.servlet;

import com.alibaba.fastjson.JSON;
import com.wanho.qz103.hrsaas.commons.factory.BeanFactory;
import com.wanho.qz103.hrsaas.commons.vo.Action;
import com.wanho.qz103.hrsaas.commons.vo.R;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet(name = "DispatcherServlet",urlPatterns = "/api/*")
public class DispatcherServlet extends HttpServlet {
    /**
     * 接受 请求
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //设置请求 编码 响应类型
            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/josn;charset=UTF-8");
            //获得请求路径  /api/sys/role
            String requestURI = request.getRequestURI();
            // 去掉 /api
            requestURI = requestURI.substring("/api".length()) ;
            // 请求方式  目前servlet版本不支持 put delete 请求  伪装  post请求：  _method="post"  "put"  "delete"
            String requestMethod =  request.getHeader("_method");
            // 获得 Action 实例
            Action action = BeanFactory.getAction(requestURI, requestMethod);
            // 获得方法对象
            Method execMethod = action.getExecMethod();
            // 获得 controller 对象
            Object controllerInstance = action.getControllerInstance();
            // 反射调用
            R r = (R) execMethod.invoke(controllerInstance, request);
            // 响应 json格式数据
            String json = JSON.toJSONString(r);
            PrintWriter writer = response.getWriter();
            writer.write(json);
            writer.flush();
            writer.close();
           // System.out.println("处理之后的路径:"+requestURI);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
